﻿/// <reference path="jquery-2.0.3.js" />
/// <reference path="LiberUI.Base.js" />
/// <reference path="LiberUI.js" />

//#region 输入验证框架
function Validater(_opt) {
	/// <summary>
	/// 创建一个输入验证器负责为一组输入元素或控件提供前端合法性验证
	/// </summary>
	/// <returns type="Validater">一个输入验证器</returns>
    var ins = this;
    var items = [];
    var hasError = false;

    var checkItem = function (i) {
        if (i && i.Fn && i.Fn(this) === false) {
            ins.showTip(i.$Elm, i.$Tip, "error", i.ErrInfo);
            if (i.AllowBlur === false) {
                i.$Elm.focus();
            }
        }
        else {
            ins.showTip(i.$Elm, i.$Tip, "pass", i.PassInfo);
        }
    };

    var onItemBlur = function (ev) {
        var i = $(this).data("validater");
        if (i) {
            checkItem(i);
        }
    };

    this.check = function () {
        items.forEach(function (i) {
            if (i.Fn) {
                hasError = i.Fn(this) || false;
            }
        });
        return hasError;
    };

    this.showTip = function ($elm,$tip, tipType, tipInfo) {
        /// <summary>
        /// 显示检查结果的默认方式
        /// </summary>
        /// <param name="$elm" type="type">检查目标</param>
        /// <param name="tipType" type="type">检查结果类型[error,pass,checking]</param>
        /// <param name="tipInfo" type="type">检查结果</param>
        $elm.removeClass("pass error checking").addClass(tipType);
        if (tipInfo) {
            if (ObjHelper.IsElement($tip)) {
                $tip.removeClass("pass error checking");
                $tip.addClass(tipType).vl(tipInfo).css("visibility", "");
            }
            else if (ObjHelper.IsFunc($tip)) {
                $tip($elm, tipType, tipInfo);
            }
            else {

            }
        }
        else {
            if (ObjHelper.IsElement($tip)) {
                $tip.removeClass("pass error checking").css("visibility", "hidden");
            }
            else if (ObjHelper.IsFunc($tip)) {
                $tip($elm, tipType, tipInfo);
            }
            else {

            }
        }
    };

    this.noEmpty = function ($elm,$tipElm,_errInfo,_passInfo,_onBlur,_allowBlur) {
        /// <summary>
        /// 不能为空内容
        /// </summary>
        /// <param name="$elm" type="type"></param>
        /// <param name="$tipElm" type="jquery dom">用于显示提示信息的DOM或方法</param>
        /// <param name="_errInfo" type="type"></param>
        /// <param name="_passInfo" type="type"></param>
        /// <param name="_onBlur" type="type"></param>
        var i = {
            $Elm: $($elm).eq(0),
            $Tip:$tipElm,
            PassInfo: _passInfo,
            ErrInfo: _errInfo,
            AllowBlur:_allowBlur,
            Fn:ValidateRule.NoEmpty
        }
        i.$Elm.data("validater", i);
        if (_onBlur === true&&i.$Elm.length==1) {
            i.$Elm.on("blur", onItemBlur);
        }
        items.push(i);
        return ins;
    };

    this.email = function ($elm, _errInfo, _passInfo, _onBlur) {
        /// <summary>
        /// 必须是电子邮箱格式
        /// </summary>
        /// <param name="$elm" type="type"></param>
        /// <param name="_errInfo" type="type"></param>
        /// <param name="_passInfo" type="type"></param>
        /// <param name="_onBlur" type="type"></param>
        return ins;
    };

    this.ajax = function ($elm,_url,_checkingInfo,_passInfo,_onBlur) {
        /// <summary>
        /// 使用后台方法验证
        /// </summary>
        /// <param name="$elm" type="type"></param>
        /// <param name="_url" type="type">后台验证地址</param>
        /// <param name="_checkingInfo" type="type"></param>
        /// <param name="_onBlur" type="type"></param>
        return ins;
    };
    return this;
}
Validater.prototype = {
    "_showTip": function ($elm, tipType, tipInfo) {

    },
    "makeItem": function ($elm, _passInf, _errInfo,_onBlur) {
        var itm = {};
        if (ObjHelper.IsElement($elm)) {
            itm.$Elm = $elm;
        }
        else if ($elm.instanceOf(LController)) {

        }
        return itm;
    }
}

var ValidateRule = {
    NoEmpty: function () {
        var v = this.$Elm.vl();
        if (!ObjHelper.IsEmpty(v)) {
            return true;
        }
        else {
            return false;
        }
    },
    IsDate: function () {
        var v = this.$Elm.vl();
        if (ObjHelper.IsEmpty(v)) {
            return false;
        }
        var d = new Date(v.toString());
        return d !== undefined&&d!='Invalid Date';
    },
    IsEmail: function () {
        var v = this.$Elm.vl();
        if (ObjHelper.IsEmpty(v)) {
            return false;
        }
        else if (/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(v)) {
            return true;
        }
        else {
            return false;
        }
    },
}
//#endregion

//#region 按指定间隔时间循环执行DOM操作的管道
function DomPiper(_delay, _interval, _parentElm, _children, _fn) {
    /// <summary>
    /// 按指定间隔时间循环执行DOM操作的管道
    /// </summary>
    /// <param name="_delay"></param>
    /// <param name="_interval"></param>
    /// <param name="_parentElm"></param>
    /// <param name="_children"></param>
    /// <param name="_fn"></param>
    var delay = _delay ? _delay : 100;
    var interval = _interval ? _interval : 250;
    var $parent = _parentElm;
    //if (!$.isArray(_children)) {
    //    return;
    //}
    var $children = $(_children);
    var fn = _fn;
    var index = 0;
    var worker = null;

    function doit() {
        //var c = $children.shift();
        var c = $children.eq(index);
        index++;
        if (c) {
            fn($parent, c);
            clearTimeout(worker);
            worker= setTimeout(doit, interval);
        }
        else {
            dispose();
        }
    };
    function dispose() {
        $parent = null;
        $children = [];
        fn = null;
        if (worker !== null) {
            clearTimeout(worker);
            worker = null;
        }
    };
    worker= setTimeout(doit, delay);
    return;
};
//#endregion

//#region ajax请求需求重新登录时的自动处理
var unhandled = [];
var loginHandler = null;
var onAjaxLoginEnd = function (ev) {
    console.log("另开窗口登录完毕", unhandled);
};
Ajax = {
    'GetJSON': function (_url, _params, callback) {
        var aj = {
            type: "GET",
            dataType:"json",
            url: _url,
            data: _params
        };
        new AjaxHandler(aj,callback);
    },
    'Post': function (_url, _data, callback) {
        var aj = {
            type: "GET",
            dataType: "json",
            url: _url,
            data: _data
        };
        new AjaxHandler(aj,callback);
    },
    'AjaxLoginUrl':"/Index.html"
};

function AjaxHandler(aj, callback) {
    var ins = this;
    var onError = function (ev) {
        if (ev.status == "401") {
            //TODO:启动异步登录过程
            if (loginHandler == null) {
                loginHandler = window.open(Ajax.AjaxLoginUrl);
                loginHandler.onunload = onAjaxLoginEnd;
            }
        }
    };
    var onAjaxSuccess = function (ev) {
        if (onSucess) {
            onSucess(ev);
        }
        onSucess = null;
        ajaxItem = null;
    };
    var ajaxItem = aj;
    var onSucess = callback;
    
    aj.error = onError;
    aj.success = onAjaxSuccess;
    $.ajax(aj);

    this.Execute = function () {
        $.ajax(aj);
    };
};
//#endregion

function ErrFormate(res,errSrc, errCode, errData) {
    /// <summary>
    /// 按资源格式化错误信息
    /// </summary>
    /// <param name="errSrc" type="type"></param>
    /// <param name="errCode" type="type"></param>
    /// <param name="errData" type="type"></param>
    /// <returns type=""></returns>
    if (res[errSrc]) {
        if (res[errSrc][errCode]) {
            var msg = res[errSrc][errCode];
            if (typeof (msg) =='object') {
                var infos=[];
                for(var i in errData){
                    infos.push(msg[errData[i]]);
                }
                return infos;
            }
            else {
                return msg;
            }
        }
        else {
            return "非常抱歉，发生了预料之外的错误。我们已记录并通知管理人员，请您稍后再来";
        }
    }
    else {
        return "非常抱歉，发生了预料之外的错误。我们已记录并通知管理人员，请您稍后再来";
    }
}